# _*_ coding : utf-8 _*_
# @Time : 2023/12/6 20:02
# @Author : 韩宗森
# @File : 14_handler处理器的基本使用
# @Project : pythonProject

# 需求使用handler来访问百度获取网页源码

import urllib.request

url = 'https://www.baidu.com/'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
}

# 请求对象的定制
request = urllib.request.Request(url=url, headers=headers)

# handler  build_opener   open
# ( 1 )获取hanlder对象
handler = urllib.request.HTTPHandler()

# (2)获取opener对象
opener = urllib.request.build_opener(handler)

# (3)调用open方法
response = opener.open(request)

# 获取响应的内容
content = response.read().decode('utf-8')

print(content)
# 数据下载到本地
